package com.mj.haier.rrskx.web.rest;

import com.codahale.metrics.annotation.Timed;
import com.mj.haier.rrskx.domain.AzOrderTitleFin;
import com.mj.haier.rrskx.domain.BdSwitcher;
import com.mj.haier.rrskx.repository.AzOrderTitleFinRepository;
import com.mj.haier.rrskx.repository.BdSwitcherRepository;
import com.mj.haier.rrskx.repository.search.AzOrderTitleFinSearchRepository;
import com.mj.haier.rrskx.web.rest.errors.BadRequestAlertException;
import com.mj.haier.rrskx.web.rest.util.HeaderUtil;
import com.mj.haier.rrskx.web.rest.util.PaginationUtil;
import io.github.jhipster.web.util.ResponseUtil;
import io.shardingsphere.core.api.HintManager;
import io.shardingsphere.core.hint.HintManagerHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.net.URI;
import java.net.URISyntaxException;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

import static org.elasticsearch.index.query.QueryBuilders.*;

/**
 * REST controller for managing AzOrderTitleFin.
 */
@RestController
@RequestMapping("/api")
public class AzOrderTitleFinResource {

    private final Logger log = LoggerFactory.getLogger(AzOrderTitleFinResource.class);

    private static final String ENTITY_NAME = "microRrskxAzOrderTitleFin";

    private final AzOrderTitleFinRepository azOrderTitleFinRepository;

    private final AzOrderTitleFinSearchRepository azOrderTitleFinSearchRepository;

    private final HintManager hintManager;

    private final BdSwitcherRepository bdSwitcherRepository;

    public AzOrderTitleFinResource(AzOrderTitleFinRepository azOrderTitleFinRepository, AzOrderTitleFinSearchRepository azOrderTitleFinSearchRepository, BdSwitcherRepository bdSwitcherRepository) {
        this.azOrderTitleFinRepository = azOrderTitleFinRepository;
        this.azOrderTitleFinSearchRepository = azOrderTitleFinSearchRepository;
        this.hintManager = HintManager.getInstance();
        this.bdSwitcherRepository = bdSwitcherRepository;
    }

    /**
     * POST  /az-order-title-fins : Create a new azOrderTitleFin.
     *
     * @param azOrderTitleFin the azOrderTitleFin to create
     * @return the ResponseEntity with status 201 (Created) and with body the new azOrderTitleFin, or with status 400 (Bad Request) if the azOrderTitleFin has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/az-order-title-fins")
    @Timed
    public ResponseEntity<AzOrderTitleFin> createAzOrderTitleFin(@RequestBody AzOrderTitleFin azOrderTitleFin) throws URISyntaxException {
        log.debug("REST request to save AzOrderTitleFin : {}", azOrderTitleFin);
        if (azOrderTitleFin.getOrderCode() != null) {
            throw new BadRequestAlertException("A new azOrderTitleFin cannot already have an OrderCode", ENTITY_NAME, "ordercodeexists");
        }
        AzOrderTitleFin result = azOrderTitleFinRepository.save(azOrderTitleFin);
        azOrderTitleFinSearchRepository.save(result);
        return ResponseEntity.created(new URI("/api/az-order-title-fins/" + result.getOrderCode()))
            .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getOrderCode().toString()))
            .body(result);
    }

    /**
     * PUT  /az-order-title-fins : Updates an existing azOrderTitleFin.
     *
     * @param azOrderTitleFin the azOrderTitleFin to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated azOrderTitleFin,
     * or with status 400 (Bad Request) if the azOrderTitleFin is not valid,
     * or with status 500 (Internal Server Error) if the azOrderTitleFin couldn't be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/az-order-title-fins")
    @Timed
    public ResponseEntity<AzOrderTitleFin> updateAzOrderTitleFin(@RequestBody AzOrderTitleFin azOrderTitleFin) throws URISyntaxException {
        log.debug("REST request to update AzOrderTitleFin : {}", azOrderTitleFin);
        if (azOrderTitleFin.getOrderCode() == null) {
            throw new BadRequestAlertException("Invalid orderCode", ENTITY_NAME, "ordercodenull");
        }
        AzOrderTitleFin result = azOrderTitleFinRepository.save(azOrderTitleFin);
        azOrderTitleFinSearchRepository.save(result);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, azOrderTitleFin.getOrderCode().toString()))
            .body(result);
    }

    /**
     * GET  /az-order-title-fins : get all the azOrderTitleFins.
     *
     * @param pageable the pagination information
     * @return the ResponseEntity with status 200 (OK) and the list of azOrderTitleFins in body
     */
    @GetMapping("/az-order-title-fins")
    @Timed
    public ResponseEntity<List<AzOrderTitleFin>> getAllAzOrderTitleFins(Pageable pageable) {
        log.debug("REST request to get a page of AzOrderTitleFins");

        Optional<BdSwitcher> bdSwitcher = bdSwitcherRepository.findBySwitcherValue("12002");
        hintManager.addTableShardingValue("az_order_title_fin", "", bdSwitcher.get().getSwitcherKey());
        Page<AzOrderTitleFin> page = azOrderTitleFinRepository.findAll(pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/az-order-title-fins");
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }

    @GetMapping("az-order-title-fins/byTrade/{trade}")
    @Timed
    public List<AzOrderTitleFin> getTop100AzOrderTitleFins(@PathVariable String trade){
        log.debug("REST request to get list of AzOrderTitleFins");

        Optional<BdSwitcher> bdSwitcher = bdSwitcherRepository.findBySwitcherValue(trade);
        hintManager.addTableShardingValue("az_order_title_fin", "", bdSwitcher.get().getSwitcherKey());
        return azOrderTitleFinRepository.findAll();
    }

    /**
     * GET  /az-order-title-fins/:orderCode : get the "orderCode" azOrderTitleFin.
     *
     * @param orderCode the id of the azOrderTitleFin to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the azOrderTitleFin, or with status 404 (Not Found)
     */
    @GetMapping("/az-order-title-fins/{orderCode}")
    @Timed
    public ResponseEntity<AzOrderTitleFin> getAzOrderTitleFin(@PathVariable String orderCode) {
        log.debug("REST request to get AzOrderTitleFin : {}", orderCode);
        Optional<AzOrderTitleFin> azOrderTitleFin = azOrderTitleFinRepository.findByOrderCode(orderCode);
        return ResponseUtil.wrapOrNotFound(azOrderTitleFin);
    }

    /**
     * DELETE  /az-order-title-fins/:orderCode : delete the "id" azOrderTitleFin.
     *
     * @param orderCode the id of the azOrderTitleFin to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/az-order-title-fins/{orderCode}")
    @Timed
    public ResponseEntity<Void> deleteAzOrderTitleFin(@PathVariable String orderCode) {
        log.debug("REST request to delete AzOrderTitleFin : {}", orderCode);

        azOrderTitleFinRepository.deleteByOrderCode(orderCode);
        azOrderTitleFinSearchRepository.deleteByOrderCode(orderCode);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, orderCode.toString())).build();
    }

    /**
     * SEARCH  /_search/az-order-title-fins?query=:query : search for the azOrderTitleFin corresponding
     * to the query.
     *
     * @param query the query of the azOrderTitleFin search
     * @param pageable the pagination information
     * @return the result of the search
     */
    // @GetMapping("/_search/az-order-title-fins")
    // @Timed
    // public ResponseEntity<List<AzOrderTitleFin>> searchAzOrderTitleFins(@RequestParam String query, Pageable pageable) {
    //     log.debug("REST request to search for a page of AzOrderTitleFins for query {}", query);
    //     Page<AzOrderTitleFin> page = azOrderTitleFinSearchRepository.search(queryStringQuery(query), pageable);
    //     HttpHeaders headers = PaginationUtil.generateSearchPaginationHttpHeaders(query, page, "/api/_search/az-order-title-fins");
    //     return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    // }

}
